<template>
	<view class="spell-skill-wrapper" v-if="showSecKillList">
		<view class="spell-skill-page flex-y-c" :style="backgroundStyle">
			<!-- <image class="spell-skill-bg" src="https://resource.migudm.cn/group1/M00/CE/EA/ooYBAGPGR22ALCjnAANeE89nFWg543.png"></image> -->
			<spell-kill-time v-if="!isDetailPage&&!ifSingleSpell && timeDataList.length" @selectTime="selectTime" :timeDataList="timeDataList"
				:minNearTime="minNearTime" :buyingTime='buyingTime' :currentTime="currentTime" :currentIndex="currentIndex" :type="type" :custom="isCustom" :timeAxis="timeAxis" :timeStyle="activityConfig.timeStyle || '1'"></spell-kill-time>
			<!-- 新加多数组 -->
			<scroll-view :scroll-into-view="scrollId" @scroll="outsideScroll" scroll-y="1" :scroll-top="newscrollTop" class="spell-kill-list">
				<view :id="'scrollView'+nindex" v-for="(nitem, nindex) in oneDayAcitvityList" >
					<view v-if="!isDetailPage&&(oneDayAcitvityList.length!=1||timeDataList.length!=1)" class="active-title">
						<view class='active-title__line' :class="[{'custom-text__line':isCustom,'beginMinute__line':getStatusForm(nitem.activity,nindex) == '即将开始'}]"></view>
						<text class='active-title__name' :class="[{'custom-text':isCustom,'beginMinute':getStatusForm(nitem.activity,nindex) == '即将开始'}]">{{ nitem.activity.effectiveTime|timeForm('HH:MM')}}  {{getStatusForm(nitem.activity,nindex)}}</text>
					</view>
					<!-- <view > -->
						<view class='downTimeBox' v-if="timeDataList.length && (showActivityName || showTimeDown)"
							:class="['spell-skill-content', 'flex-x-c', {'white-bcg': bcgChange}]">
							<view :class="showActivityName?'':'new_end-time-wrapper'" class="end-time-wrapper flex-x-c" :style="{color: !isCustom? '#333':'#333'}">
								<view class="title line-1" :class="[isCustom ? 'title-custom' : '']" v-if="showActivityName">{{ nitem.activity.name }}</view>
								<view class="flex-x-c">
									<template v-if="showTimeDown">
										<text class="end-text">{{ nitem.activity.isStart ? '距结束' : '距开始' }}</text>
										<countDown :bgColor="isCustom ? '#FF004F' : '#FF004F'" color="#000" :endTime="nitem.activity.endTime" @timeOut="init()"></countDown>
									</template>
									<template v-if="!isDetailPage && nitem.objectItems.length > 5">
										<image @click="clickMore(nitem.activity)" class="title-more" :src="'malleoc/activity/icon_more_line.png'| imgUrlForm"></image>
										<!-- <image @click="clickMore(nitem.activity)" class="title-more" :src="'malleoc/activity/icon_more_line_white.png'| imgUrlForm" v-else></image> -->
									</template>
								</view>
							</view>
						</view>
						<view v-if="nitem.objectItems.length">
							<view class="shadow" v-if="showShowdow"></view>
							<scroll-view @scroll="dateScroll" scroll-y="1" class="scroll-container">
								<view class="shadow" v-if="showShowdow"></view>
								<view class="inner-spell">
									<template v-for="(item, index) in nitem.objectItems">
										<spell-kill-item
											v-if="isDetailPage || (!isDetailPage && index < 5)"
											:key="index"
											:spellKKillItem="item"
											:currentActivity="currentActivity"
											:isStart="nitem.activity.isStart"
											:endTime="nitem.activity.endTime"
											:data-ui="index"
											:currentTime="currentTime" :type="type" :index="index" @refresh="init(true)">
										</spell-kill-item>
									</template>
									<view class="list-more" v-if="!isDetailPage && nitem.objectItems.length > 5" @click="clickMore(nitem.activity)">
										<!-- 更多活动商品 -->
										<image class="list-more-image" src="https://resource.migudm.cn/group1/M00/D0/D9/ooYBAGPoipuAIa_oAAAHk6YviOE328.png"></image>
									</view>
								</view>
							</scroll-view>
						</view>
					<!-- </view> -->
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	import countDown from "@/components/countDown.vue";
	import spellKillTime from "./spell-kill-time.vue";
	import spellKillItem from "./spell-kill-item.vue";
	export default {
		components: {
			countDown,
			spellKillTime,
			spellKillItem
		},
		props: {
			//01 秒杀全网 03秒杀会员 02拼团全网 04拼团会员
			type: {
				type: String,
				default: ''
			},
			config: {
				type: String,
				default: ''
			},
			enterId:  {
				type: String,
				default: ''
			},
			//活动id
			activityIdList: {
				type: Array,
				default: () => {
					return []
				}
			},
			// 活动参与者类型，1：全部用户，2: 会员专场
			participantType: {
				type: Number,
				default: 1
			},
			// 是否列表聚合页
			isDetailPage: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				currentItem:{},
				scrollId:'',
				old: {
					scrollTop: 0
				},
				newscrollTop:150,
				oneDayAcitvityList:[],//模拟数据
				buyingTime:'',//当前抢购中的时间
				showSecKillList: false,
				activityId: '',
				backgroundStyle: 'background:#F6F6F6',
				// backgroundStyle: 'background:#ff72d5',
				timeAxis: 'background:#fff',
				currentTime: "", //获取当前时间
				bcgChange: false,
				timeDataList: [], //时间列表
				currentIndex: 0,
				nameShowIndex:0,
				minNearTime: 0, // 距离当日最小的时间
				endTime: null, // 倒计时时间
				isStart: true, // 距开始/结束显示字段
				spellKillList: [], // 商品列表
				// 分页数据start
				totalPages: 7, // 总页数
				pageNo: 1, // 第几页
				pageSize: 10, // 每页几条
				isLodingAll: false,
				showShowdow: false,
				ifSingleSpell: false, // 是否指定单场内
				activityName: '',
				currentActivity: {},
				// 分页数据end
			}
		},
		mounted(){

		},
		created() {
			this.init()

		},
		computed: {
			// 组件页面配置信息
			activityConfig() {
				let config = {
					detailConfiguration: 1
				}
				try {
					config = JSON.parse(this.config)
				} catch (error) {}
				return config
			},
			// 是否显示倒计时
			showTimeDown() {
				if (this.isDetailPage && this.activityConfig.activityModule == 1){
					if(this.activityConfig.ConfigIfCountDown == 1) return true
					return false
				}
				if (this.activityConfig.ifCountDown == 1)  return true
				return false
			},
			// 是否显示活动名称
			showActivityName() {
				if (this.isDetailPage && this.activityConfig.activityModule == 1){
					if(this.activityConfig.ConfigIfShowName == 1) return true
					return false
				}
				if (this.activityConfig.ifShowName == 1)  return true
				return false
			},
			// 是否底图自定义，设置对应的背景
			isCustom() {
				const config = this.activityConfig
				if (config.activityModule == 2 && config.isfooterImage == 2) {
					if(config.isTimeAxisBack == 1 && config.isTimeAxisBackImg){
						this.timeAxis = 'background-image:url('+config.isTimeAxisBackImg+');background-repeat:no-repeat;background-size:100% 100%'
					} else if(config.isTimeAxisBack == 2 && config.isTimeAxisBackColor){
						this.timeAxis = 'background:'+config.isTimeAxisBackColor
					}
					if(config.componentBack == 1 && config.componentBackImg){
						this.backgroundStyle = 'background-image:url('+config.componentBackImg+');background-repeat:no-repeat;background-size:100%'
					} else if(config.componentBack == 2 && config.componentBackColor){
						this.backgroundStyle = 'background:'+config.componentBackColor
					}
					return true
				}
				if (config.detailConfiguration == 2 && this.isDetailPage) {
					if(config.configIsTimeAxisBack == 1 && config.configIsTimeAxisBackImage){
						this.timeAxis = 'background-image:url('+config.configIsTimeAxisBackImage+');background-repeat:no-repeat;background-size:100% 100%'
					} else if(config.configIsTimeAxisBack == 2 && config.configIsTimeAxisBackColor){
						this.timeAxis = 'background:'+ config.configIsTimeAxisBackColor
					}
					if(config.isConfigBack == 1 && config.isConfigBackImage){
						this.backgroundStyle = 'background-image:url('+config.isConfigBackImage+');background-repeat:no-repeat;background-size:100%'
					} else if(config.isConfigBack == 2 && config.isConfigBackColor){
						this.backgroundStyle = 'background:'+config.isConfigBackColor
					}
					return true
				}
				return false
			}
		},
		// inject:['showBeginMinuteBtn'],
		inject: {
			showBeginMinuteBtn: { value: "showBeginMinuteBtn", default: null },
		},
		methods: {
			// 判断活动状态
			getStatusForm(e,nindex){
				let effectiveTime = new Date(this.$utils.formatTime(e.effectiveTime)).getTime();
				// let expireTime = new Date(this.$utils.formatTime(e.expireTime)).getTime();

				// 开始时间小于等当前时间,已开始
				if(effectiveTime<=this.currentTime){
					return this.currentIndex==this.nameShowIndex&&nindex==0?'抢购中':'已开始';
				}else{
					return '即将开始'
				}
			},
			outsideScroll(e) {
				// console.log(e)
				this.old.scrollTop = e.detail.scrollTop
			},
			getGoTop(e) {
				// 解决view层不同步的问题
				this.newscrollTop = this.old.scrollTop
				this.$nextTick(()=>{
					this.newscrollTop = 0
				})
			},
			getGoBuying(){
				this.scrollId='';
				this.$nextTick(()=>{
					this.scrollId='scrollView1';
				})
			},
			async init(refresh) {
				let sysTime = await this.$utils.getNowTime();
				if (sysTime.sysTime) {
					this.currentTime = new Date(
						this.$utils.formatTime(sysTime.sysTime)
					).getTime();
				} else {
					this.currentTime = new Date().getTime();
				}


				this.newGetTimeList(refresh).then(res => {
					// 聚合页单场活动全部商品
					if(this.isDetailPage){
						this.getSpellKillList();
					}else{
						this.getQueryCurrentSeckillList(res);
					}
				}).catch((res)=>{
					if (res = 'empty') console.log('空列表');
				});

			},
			// 倒计时结束
			timeOut() {
				// this.isStart = true
			},
			// ****新时间列表获取***
			newGetTimeList(refresh){
				return new Promise((resolve, reject) => {
					const participantType = this.participantType
					const paramas = {
						activityIdList: this.activityIdList,
						participantType: participantType
					};
					// if (!this.isDetailPage) paramas.customPage = true
					this.$request("activity/querySeckillDateList", paramas).then(res => {

						const timeDataList = res.data.dateList;
						this.buyingTime = res.data.currentDate


						if (timeDataList.length == 0) {
							reject('empty')
							return
						}
						this.showSecKillList = true
						if (timeDataList.length == 1) this.ifSingleSpell = true
						const enterId = this.enterId
						let enterIndex = null


						res.data.dateList.forEach((ele,index)=>{
							if(ele==res.data.currentDate){
								this.currentIndex = index;
								this.nameShowIndex = index;
							}
						})

						this.timeDataList = timeDataList

						resolve(res.data.currentDate||timeDataList[0]);
					});
				});
			},
			// ****新根据日期返回所有的活动场次****
			getQueryCurrentSeckillList(e) {
				this.oneDayAcitvityList = [];
				// const spellKillItem = this.timeDataList.filter(item => item.id == e)
				uni.showLoading({
					title: "加载中",
					mask: true
				});
				let paramas = {
					activityIdList: this.activityIdList,
					// activityId: e,
					currentDate:e,
					participantType: this.participantType
				};
				//秒杀列表
				this.$request("activity/queryCurrentSeckillList", paramas).then(data => {

					this.oneDayAcitvityList = data.data;
					uni.hideLoading();

					let hasNoBegin = false;   //是否有即将开始的场
					this.oneDayAcitvityList.forEach(subres=>{
						let effectiveTime = new Date(this.$utils.formatTime(subres.activity.effectiveTime)).getTime();
						let expireTime = new Date(this.$utils.formatTime(subres.activity.expireTime)).getTime();

						subres.activity.isStart = this.currentTime > effectiveTime ? true : false

						subres.activity.endTime = subres.activity.isStart ? expireTime : effectiveTime;

						hasNoBegin = effectiveTime>this.currentTime
					})



					// 获取即将开始的距离顶部高度，，
					this.$nextTick(()=>{
						// 是今天&&有即将开始的场次，需要显示，，
						if(this.buyingTime == e&&hasNoBegin){
							let query = uni.createSelectorQuery();
							query.select('.beginMinute').boundingClientRect(ele => {
								if(ele){
									this.showBeginMinuteBtn(true,ele.top-uni.upx2px(100))
								}
							}).exec();
						}else{
							this.showBeginMinuteBtn(false)
						}
					})

				});

			},
			// 时间列表获取
			getTimeList(refresh) {
				return new Promise((resolve, reject) => {
					const participantType = this.participantType
					const paramas = {
						activityIdList: this.activityIdList,
						participantType: participantType
					};
					if (!this.isDetailPage) paramas.customPage = true
					this.$request("activity/queryActivityList", paramas).then(res => {
						const timeDataList = res.data.filter(item => {
							// 过滤列表，会员可看非会员活动
							return item.participantType < participantType || item.participantType == participantType
						});
						
						if (timeDataList.length == 0) {
							reject('empty')
							return
						}
						this.showSecKillList = true
						if (timeDataList.length == 1) this.ifSingleSpell = true
						const enterId = this.enterId
						let enterIndex = null
						// 获取时间数组
						timeDataList.forEach((item, index) => {
							if (enterId === item.id) enterIndex = index
							// 后台时间转化为时间戳
							item.exEffectiveTime = item.effectiveTime
							item.exExpireTime = item.expireTime
							item.effectiveTime = new Date(this.$utils.formatTime(item.effectiveTime)).getTime();
							item.expireTime = new Date(this.$utils.formatTime(item.expireTime)).getTime();
							item.formShowDate = this.formDate(item.effectiveTime)
							item.isStart = this.currentTime > item.effectiveTime ? 1 : 0
						});
						let currentIndex = 0
						for (let i = 0; i < timeDataList.length; i++) {
							if (this.ifSingleSpell) {
								if (this.activityId == timeDataList[i].id) currentIndex = i
							} else {
								if (!timeDataList[i].isStart) break
								if (!timeDataList[i + 1] || (timeDataList[i].isStart && !timeDataList[i +
										1].isStart)) {
									timeDataList[i].isStart = 2
									currentIndex = i;
								}
							}
						}
						
						if (enterIndex != null) currentIndex = enterIndex

						if (refresh) {
							currentIndex = this.currentIndex
						} else {
							this.currentIndex = currentIndex;
						}
						const currentItem = timeDataList[currentIndex]
						this.endTime = currentItem.isStart ? currentItem.expireTime : currentItem
							.effectiveTime;
						this.isStart = timeDataList[currentIndex].isStart ? true : false
						this.activityId = timeDataList[currentIndex].id
						this.activityName = timeDataList[currentIndex].name
						this.minNearTime = timeDataList[currentIndex].effectiveTime
						// 筛选出当日以前的时间存为数组（即开始的活动时间数组）
						this.timeDataList = timeDataList
						resolve(this.activityId);
					});
				});
			},
			formDate(time) {
				const beginTime = new Date(time)
				const beginDay = beginTime.setHours(0, 0, 0, 0);
				const today = new Date().setHours(0, 0, 0, 0);
				if (beginDay - today == 86400000) return '明天'
				if (beginDay - today > 86400000) {
					const year = beginTime.getMonth() + 1
					const date = beginTime.getDate()
					return year + '/' + date
				}
				return false
			},
			// 秒杀商品列表获取
			getSpellKillList(res) {
				this.oneDayAcitvityList = [];
				// const spellKillItem = this.timeDataList.filter(item => item.id == res)
				uni.showLoading({
					title: "加载中",
					mask: true
				});
				let paramas = {
					activityId: this.enterId,
					participantType: this.participantType
				};
				//秒杀列表
				this.$request("activity/queryActivityDetail", paramas).then(data => {

					let effectiveTime = new Date(this.$utils.formatTime(data.activity.effectiveTime)).getTime();
					let expireTime = new Date(this.$utils.formatTime(data.activity.expireTime)).getTime();
					data.activity.isStart = this.currentTime > effectiveTime ? true : false
					data.activity.endTime = data.activity.isStart ? expireTime : effectiveTime;

					this.oneDayAcitvityList = [{
						objectItems:data.objectItems|| [],
						activity:data.activity|| {}
					}]

					uni.hideLoading();
				});

			},
			// 时间选择
			async selectTime(obj) {
				this.currentIndex = obj.currentIndex;
				const sysTime = await this.$utils.getNowTime();
				if (sysTime.sysTime) {
					this.currentTime = new Date(
						this.$utils.formatTime(sysTime.sysTime)
					).getTime();
				} else {
					this.currentTime = new Date().getTime();
				}

				this.getQueryCurrentSeckillList(obj.timeItem);

			},
			dateScroll(e) {
				this.showShowdow = e.detail.scrollTop > 5
			},
			clickMore (e) {
				let activityId = e.id;
				this.$routeUtils.navigateTo({
					url: `/package_activity/spell/spellKillList?type=${this.type}&participanttype=${this.participantType}&activityidlist=${this.activityIdList.join(",")}&config=${this.config}&enterId=${activityId}`
				})

				// this.$routeUtils.navigateTo({
				// 	url: `/package_activity/spell/spellKillList?type=${this.type}&participanttype=${this.participantType}&activityidlist=${this.activityIdList.join(",")}&config=${this.config}&enterId=${this.activityId}`
				// })
			},
		},
		onPageScroll(e) {
			// 需求变为滚动背景不变色
			// e.scrollTop >= 40 ? this.bcgChange = true : this.bcgChange = false
		}
	}
</script>

<style lang="scss">
	.spell-skill-wrapper {
		text-align: left;
	}

	// 背景
	.spell-skill-bg {
		position: absolute;
		width: 100%;
		height: 488rpx;
		top: 0;
		left: 0;
		z-index: 0;
	}

	.spell-skill-page {
		margin-top: -2px;
		position: relative;
		height: 100%;
		padding-bottom:10rpx;
	}

	// 页面-内容区
	.spell-skill-content {
		position: relative;
		padding: 0 24rpx;
		box-sizing: border-box;
		height: 106rpx;
		// width: 750rpx;
		width:100%;
		background-color: rgba(255, 255, 255, 0);
		transition: all 500ms ease-in;
		justify-content: space-between;

		&.white-bcg {
			background-color: #f6f6f6;
		}

		.end-time-wrapper {
			width: 100%;
			justify-content: space-between;
			color: #fff;
			font-size: 14rpx;

			.title {
				font-size: 28rpx;
				max-width: 280rpx;
				color: #333;
				font-weight: bold;

				&.title-custom {
					color: #000;
				}
			}

			.end-text {
				margin-right: 4rpx;
				font-size: 24rpx;
				color:#000;
			}
		}

		.lodingAll {
			text-align: center;
			margin: 10rpx 0;
		}
	}

	.spell-kill-list {
		border-radius: 8rpx;
		flex: 1;
		overflow-y: auto;
		position: relative;
		z-index: 1;
		width: 702rpx;

		.scroll-container {
			height: 100%;
		}

		.inner-spell {
			background-color: #fff;
			border-radius: 20rpx;
		}

		.shadow {
			position: absolute;
			top: -8rpx;
			height: 1rpx;
			z-index: 2;
			width: 702rpx;
			box-shadow: 0px 5px 5px 0px rgba(0, 0, 0, 1);
		}
	}

	// 单场秒杀的样式
	.single-skill {
		margin-top: 0rpx;
		padding-top: 132rpx;

		.end-time-wrapper {
			width: 100%;
			position: fixed;
			left: 0;
			padding-left: 16rpx;
			height: 132rpx;
			z-index: 10;
			background: linear-gradient(270deg, #FF5656 0%, #FF004F 100%);
		}
	}
	.title-more{
		width: 32rpx;
		height: 32rpx;
	}
	.list-more {
		display: flex;
		justify-content: center;
		padding: 24rpx 0;

		.list-more-image {
			width: 196rpx;
			height: 32rpx;
		}
	}
	.active-title{
		display: flex;
		justify-content: flex-start;
		// padding: 0 24rpx;
		width:100%;
		color:#FF004F;
		font-weight: 600;
		font-size: 32rpx;
		margin:20rpx 0;
		align-items: center;
		.active-title__name{
			padding:0 24rpx;
			color:#FF004F;
			// border-left:solid 6rpx #FF004F;
		}
		.active-title__line{
			height:28rpx;
			width:5rpx;
			border-radius: 150rpx;
			background: #FF004F;
		}
		.beginMinute{
			color: #949494;
		}
		.beginMinute__line{
			background: #949494;
		}
	}
	.downTimeBox{
		border-radius: 20rpx 20rpx 0rpx 0rpx;
		// flex: 1;
		// overflow-y: auto;
		// position: relative;
		z-index: 1;
		width: 702rpx;
		background-color: #fff;
		margin-bottom: -24rpx
	}
	.active-title{
		.custom-text {
		  padding:0 24rpx;
		  color: #fff!important;
		  // opacity: .5;
		  // border-left:solid 6rpx #fff;
		}
		.custom-text__line{
			background: #fff!important;
		}
	}
	// .fixedHead{
	// 	position: absolute;;
	// 	top: 0;
	// 	right: 0;
	// 	bottom: 0;
	// 	left: 0;
	// }
	// :class='$attrs.fragmentLength==1?"fixedHead":""'
	.downTimeBox{
		.new_end-time-wrapper{
			justify-content:flex-end;
		}
	}
</style>
